package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.mapper.UserMapper;
import com.example.onlinemusic.model.HomePage;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author 12629
 * @Date 2022/4/11 11:32
 * @Description：
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoveMusicMapper loveMusicMapper;

    @Autowired
    private MusicMapper musicMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private static final String AVATAR_UPLOAD_DIR = "A:\\code\\learn-java-ee\\music-player\\uploads\\avatars\\";

    @RequestMapping("/login1")
    public ResponseBodyMessage<User> login1 (@RequestParam String username, @RequestParam String password,
                                           HttpServletRequest request) {

        User userLogin = new User();
        userLogin.setUsername(username);
        userLogin.setPassword(password);

        User user = userMapper.login(userLogin);

        if(user == null) {
            System.out.println("登录失败！");
            return new ResponseBodyMessage<>(-1,"登录失败！",userLogin);
        }else {
            //request.getSession().setAttribute("USERINFO_SESSION_KEY",user);
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<>(0,"登录成功！",userLogin);
        }
    }


    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestParam @NonNull String username, @RequestParam @NonNull String password,
                                            HttpServletRequest request) {
        log.info("用户登录，controller");
        User user = userMapper.selectByName(username);

        if(user == null) {
            System.out.println("登录失败！");
            return new ResponseBodyMessage<>(-1,"用户名或者密码错误！",user);
        }else {
            boolean flg = bCryptPasswordEncoder.matches(password,user.getPassword());
            if(!flg) {
                return new ResponseBodyMessage<>(-1,"用户名或者密码错误！",user);
            }
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<>(0,"登录成功！",user);
        }
    }

    @RequestMapping("/register")
    public ResponseBodyMessage<User> register(@RequestParam("username") @NonNull String username,
                                              @RequestParam("nickname") String nickname,  // 改为非必填
                                              @RequestParam("email") @NonNull String email,
                                              @RequestParam("password") @NonNull String password,
                                              @RequestParam("confirmPassword") @NonNull String confirmPassword) {
        log.info("用户注册,controller");

        try {
            // 1. 参数校验
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(email) ||
                    StringUtils.isEmpty(password) || StringUtils.isEmpty(confirmPassword)) {
                return new ResponseBodyMessage<>(-1, "请输入完整的参数！");
            }

            // 2. 密码确认校验
            if (!password.equals(confirmPassword)) {
                log.error("两次输入的密码不一致!");
                return new ResponseBodyMessage<>(-1, "两次输入的密码不一致!");
            }

            // 3. 检查用户名是否已存在
            User existingUser = userMapper.selectByName(username);
            if (existingUser != null) {
                return new ResponseBodyMessage<>(-1, "用户名已存在！");
            }

            // 4. 检查邮箱是否已注册
            existingUser = userMapper.selectByEmail(email);
            if (existingUser != null) {
                return new ResponseBodyMessage<>(-1, "邮箱已被注册！");
            }

            // 5. 数据准备和密码加密
            User user = new User();
            user.setUsername(username);
            user.setNickname(StringUtils.isEmpty(nickname) ? username : nickname); // 如果昵称为空则使用用户名
            user.setEmail(email);
            user.setPassword(bCryptPasswordEncoder.encode(password));

            // 6. 插入数据库
            int result = userMapper.insert(user);
            if (result == 1) {
                log.info("用户注册成功: {}", username);
                return new ResponseBodyMessage<>(0, "注册成功！", user);
            } else {
                log.error("用户注册失败，数据库插入异常: {}", username);
                return new ResponseBodyMessage<>(-1, "注册失败，请稍后重试！");
            }
        } catch (Exception e) {
            log.error("用户注册异常: {}", e.getMessage());
            return new ResponseBodyMessage<>(-1, "系统异常，请稍后重试！");
        }
    }



    // 新增：更新播放次数接口
    @PostMapping("/updatePlayCount")
    @ResponseBody
    public ResponseBodyMessage<User> updatePlayCount(@RequestBody User user) {
        try {
            // 根据用户 ID 查询数据库中的用户
            User dbUser = userMapper.selectById(user.getId());
            if (dbUser == null) {
                return new ResponseBodyMessage<>(-1, "用户不存在");
            }
            // 播放次数 +1
            dbUser.setPlayCount(dbUser.getPlayCount() + 1);
            // 更新到数据库
            userMapper.updateById(dbUser);
            return new ResponseBodyMessage<>(0, "播放次数更新成功", dbUser);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "播放次数更新失败");
        }
    }


    // 新增: 更改头像
    @PostMapping("/avatar")
    public ResponseBodyMessage<User> updateAvatar(
            @RequestParam("username") String username,
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) {

        // 从session中获取当前登录用户
        User currentUser = (User) request.getSession().getAttribute(Constant.USERINFO_SESSION_KEY);
        if (currentUser == null) {
            return new ResponseBodyMessage<>(-1, "用户未登录");
        }

        try {
            if (file.isEmpty()) {
                return new ResponseBodyMessage<>(-1, "请选择上传的头像文件");
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return new ResponseBodyMessage<>(-1, "请上传图片类型的文件");
            }

            // 构建完整存储路径（使用绝对路径）
//            // 将文件保存到 Tomcat 的临时工作目录
//            String uploadDir = request.getServletContext().getRealPath("/uploads/avatars/");

            // 改为存储在硬盘
            String uploadDir = AVATAR_UPLOAD_DIR;
            File dir = new File(uploadDir);

            // 确保目录存在（包括父目录）
            if (!dir.exists()) {
                boolean success = dir.mkdirs(); // 使用mkdirs()创建多级目录
                if (!success) {
                    log.error("创建目录失败: {}", uploadDir);
                    return new ResponseBodyMessage<>(-1, "服务器内部错误，请稍后重试");
                }
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;
            String filePath = uploadDir + uniqueFileName;

            // 保存文件
            File dest = new File(filePath);
            file.transferTo(dest);

            // 构建可访问的URL路径（相对路径）
            String avatarUrl = "/uploads/avatars/" + uniqueFileName;
            log.info("生成的头像URL: {}", avatarUrl); // 检查日志输出是否包含完整文件名

            // 更新用户信息
            currentUser.setAvatarUrl(avatarUrl);
            userMapper.updateAvatarById(currentUser);
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY, currentUser);

            return new ResponseBodyMessage<>(0, "头像更新成功", currentUser);

        } catch (IOException e) {
            log.error("头像上传失败: {}", e.getMessage(), e); // 打印完整堆栈信息
            return new ResponseBodyMessage<>(-1, "头像上传失败，请稍后重试");
        } catch (Exception e) {
            log.error("头像更新异常: {}", e.getMessage(), e);
            return new ResponseBodyMessage<>(-1, "系统异常，请稍后重试");
        }
    }


    // 新增:个人主页显示正确的数据(收藏歌曲,上传音乐,播放次数)
    @RequestMapping("/stats")
    public ResponseBodyMessage<HomePage> getStats(HttpServletRequest request) {
        // 从session中获取当前登录用户
        User currentUser = (User) request.getSession().getAttribute(Constant.USERINFO_SESSION_KEY);
        if (currentUser == null) {
            return new ResponseBodyMessage<>(-1, "用户未登录");
        }
        // 获取当前的用户id
        HomePage homePage = new HomePage();
        homePage.setUserId(currentUser.getId());
        // 获取当前的用户播放次数
        homePage.setPlayCount(currentUser.getPlayCount());
        // 获取当前用户的收藏音乐数
        int loveMusic = loveMusicMapper.getLoveMusicNumByUserId(currentUser.getId());
        homePage.setLoveMusicNum(loveMusic);
        // 获取当前用户上传的音乐数
        int downloadMusic = musicMapper.getDownloadMusicNumByUserId(currentUser.getId());
        homePage.setDownloadMusicNum(downloadMusic);

        /**
         * TODO：获取歌单数(暂时未实现)
         */
        return new ResponseBodyMessage<>(0,"成功获取主页统计信息!",homePage);
    }

}
